<template>
  <el-drawer
    v-model="showAuth"
    title="商城权限"
    :close-on-click-modal="true"
    size="50%"
  >
    <!--form表单-->
    <el-form size="small" ref="form" :model="form" label-width="80px">
      <el-form-item label="权限列表：" v-model="form.access_id">
        <el-tree
          :data="accessList"
          show-checkbox
          node-key="access_id"
          ref="treeRef"
          :check-strictly="false"
          :default-expand-all="true"
          :default-checked-keys="form.access_id"
          :props="{ label: 'name', children: 'children',class: customNodeClass }"
          @check="handleCheckChange"
        ></el-tree>
      </el-form-item>
      <el-form-item>
        <div class="button-group">
          <el-button size="large" type="info" @click="cancelFunc"
            >取消</el-button
          >
          <el-button type="primary" size="large" @click="onSubmit"
            >提交</el-button
          >
        </div>
      </el-form-item>
      <!--提交-->
    </el-form>
  </el-drawer>
</template>

<script setup lang="ts">
import {
  appAccessApi,
  accessList as accessApi,
  setAppAccess,
} from "@/api/access.js";
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
const form = ref<any>({
  access_id: [],
});
const showAuth = ref(false);
const accessList = ref<any[]>([]);
const app_id = ref(0);
const treeRef = ref<any>(null);
const customNodeClass = (nodeData: any, node: any):string => {
  if (nodeData.subLevelCount === 0) {
    return 'is-last-level';
  }
  if (nodeData.subLevelCount === 1) {
    return 'is-penultimate-level';
  }
  return '';
};
const getMaxLevel = (nodes: any[], currentLevel = 0):number => {
  if (!nodes || nodes.length === 0) {
    return currentLevel;
  }
  return Math.max(...nodes.map(child => getMaxLevel(child.children, currentLevel + 1)));
};

const calculateSubLevelCount = (nodes: any[]):void => {
  nodes.forEach(node => {
    node.subLevelCount = getMaxLevel(node.children);
    if (node.children && node.children.length > 0) {
      calculateSubLevelCount(node.children);
    }
  });
};
onMounted(() => {
  accessApi({}).then((res) => {
    accessList.value = res.data;
    calculateSubLevelCount(accessList.value);
  });
});
const onSubmit = () => {
  setAppAccess({
    app_id: app_id.value,
    access_id: form.value.access_id,
  }).then(() => {
    ElMessage.success("权限设置成功");
    cancelFunc();
  });
};
/*监听选中*/
const handleCheckChange = (data: any, checked: any) => {
  form.value.access_id = checked.checkedKeys.concat(checked.halfCheckedKeys);
};

/*取消*/
const cancelFunc = () => {
  showAuth.value = false;
  form.value.access_id = [];
  app_id.value = 0;
};
const open = (id: number) => {
  showAuth.value = true;
  app_id.value = id;
  appAccessApi(app_id.value).then((res: any) => {
    form.value.access_id = res.data;
    treeRef.value.setCheckedKeys([]);
    // 手动设置默认选中项
    form.value.access_id.forEach((accessId:number) => {
      const node = findNodeById(accessList.value, accessId);
      if (node) {
        // 只选中父节点，不选中子节点
        treeRef.value.setChecked(node, true, false);
      }
    });
  });
};
const findNodeById = (data:any[], id:number):any=>{
  for (const node of data) {
    if (node.access_id === id) {
      return node;
    }
    if (node.children && node.children.length) {
      const foundNode = findNodeById(node.children, id);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
}
defineExpose({ open });
</script>

<style lang="scss" scoped>
.button-group {
  position: fixed;
  bottom: 10px;
  right: 30px;
  width: 200px;
  text-align: right;
}
::v-deep(.is-penultimate-level .el-tree-node__children){
  display: flex;
  flex-wrap: wrap;
}
</style>
